/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 播放列表页面视图 - 支持垂直滑动切歌
 */

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../viewmodels/music_player_view_model.dart';
import '../models/music_item_model.dart';
import '../widgets/music_widgets/album_cover_widget.dart';
import '../widgets/music_widgets/progress_slider_widget.dart';
import '../models/play_mode.dart';

/// 播放列表页面视图
/// 使用 PageView.builder 实现垂直滑动切歌功能
class PlaylistPageView extends StatefulWidget {
  /// 初始页面索引
  final int initialIndex;

  const PlaylistPageView({
    super.key,
    this.initialIndex = 0,
  });

  @override
  State<PlaylistPageView> createState() => _PlaylistPageViewState();
}

class _PlaylistPageViewState extends State<PlaylistPageView> {
  late PageController _pageController;
  bool _isUserScrolling = true; // 默认允许用户滚动触发播放
  MusicPlayerViewModel? _viewModel; // 缓存 ViewModel 引用

  @override
  void initState() {
    super.initState();

    // 初始化 PageController，优先使用传入的初始索引
    _viewModel = context.read<MusicPlayerViewModel>();
    final initialPage = widget.initialIndex > 0
        ? widget.initialIndex
        : (_viewModel!.currentIndex >= 0 ? _viewModel!.currentIndex : 0);

    _pageController = PageController(initialPage: initialPage);

    // 监听播放索引变化，同步页面位置
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _setupPlayIndexListener();
    });
  }

  /// 设置播放索引监听器
  void _setupPlayIndexListener() {
    _viewModel?.addListener(_onPlayIndexChanged);
  }

  /// 播放索引变化时的回调
  void _onPlayIndexChanged() {
    if (!mounted || _viewModel == null) return; // 检查 widget 是否仍然挂载

    final currentIndex = _viewModel!.currentIndex;

    // 如果当前页面索引与播放索引不一致，且不是用户滚动导致的，则同步页面
    if (currentIndex >= 0 &&
        _pageController.hasClients &&
        _pageController.page?.round() != currentIndex) {
      _jumpToPage(currentIndex);
    }
  }

  @override
  void dispose() {
    // 安全地移除监听器
    _viewModel?.removeListener(_onPlayIndexChanged);
    _pageController.dispose();
    _viewModel = null; // 清空引用
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer<MusicPlayerViewModel>(
        builder: (context, viewModel, child) {
          // 如果播放列表为空，显示空状态
          if (viewModel.playlist.isEmpty) {
            return _buildEmptyPlaylist();
          }

          return Stack(
            children: [
              // 主要的 PageView - 性能优化版本
              PageView.builder(
                controller: _pageController,
                scrollDirection: Axis.vertical,
                onPageChanged: (index) {
                  _handlePageChanged(index, viewModel);
                },
                itemCount: viewModel.playlist.length,
                itemBuilder: (context, index) {
                  final music = viewModel.playlist[index];
                  final isCurrentPlaying = index == viewModel.currentIndex;

                  // 使用优化的播放页面组件
                  return OptimizedMusicPlayerPage(
                    music: music,
                    isCurrentPlaying: isCurrentPlaying,
                    showRealTimeProgress: isCurrentPlaying,
                    index: index,
                  );
                },
                // 性能优化配置
                allowImplicitScrolling: true, // 允许隐式滚动
                padEnds: false, // 不在两端添加填充
              ),

              // 播放列表管理按钮
              _buildPlaylistManagementButton(viewModel),
            ],
          );
        },
      ),
    );
  }

  /// 处理页面切换
  void _handlePageChanged(int index, MusicPlayerViewModel viewModel) {
    // 防止在程序控制滚动时触发播放
    if (!_isUserScrolling) return;

    // 页面级滑动切歌
    if (index != viewModel.currentIndex) {
      viewModel.playAtIndex(index);
    }

    // 预加载逻辑：当滚动到 70% 位置时触发预加载
    if (index >= viewModel.playlist.length * 0.7) {
      viewModel.preloadNextPage();
    }

    debugPrint('页面切换到索引: $index');
  }

  /// 构建空播放列表状态
  Widget _buildEmptyPlaylist() {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.black, Colors.grey],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      child: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.queue_music_rounded,
              size: 80,
              color: Colors.white54,
            ),
            SizedBox(height: 20),
            Text(
              '播放列表为空',
              style: TextStyle(
                color: Colors.white,
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: 10),
            Text(
              '请先添加音乐到播放列表',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建播放列表管理按钮
  Widget _buildPlaylistManagementButton(MusicPlayerViewModel viewModel) {
    return Positioned(
      right: 16,
      bottom: 100,
      child: FloatingActionButton(
        onPressed: () => _showPlaylistManagementDialog(viewModel),
        backgroundColor: Colors.white.withOpacity(0.9),
        child: const Icon(
          Icons.playlist_play,
          color: Colors.black,
        ),
      ),
    );
  }

  /// 显示播放列表管理对话框
  void _showPlaylistManagementDialog(MusicPlayerViewModel viewModel) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => PlaylistManagementSheet(viewModel: viewModel),
    );
  }

  /// 跳转到指定页面（程序控制）
  void _jumpToPage(int index) {
    _isUserScrolling = false;
    _pageController
        .animateToPage(
      index,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    )
        .then((_) {
      // 动画完成后恢复用户滚动检测
      Future.delayed(const Duration(milliseconds: 100), () {
        _isUserScrolling = true;
      });
    });
  }
}

/// 播放列表管理面板
class PlaylistManagementSheet extends StatelessWidget {
  final MusicPlayerViewModel viewModel;

  const PlaylistManagementSheet({
    super.key,
    required this.viewModel,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.7,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        children: [
          // 标题栏
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(color: Colors.grey.shade300),
              ),
            ),
            child: Row(
              children: [
                const Text(
                  '播放列表',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                Text(
                  '共 ${viewModel.playlist.length} 首',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey.shade600,
                  ),
                ),
                const SizedBox(width: 16),
                TextButton(
                  onPressed: () => _showClearConfirmDialog(context),
                  child: const Text(
                    '清空',
                    style: TextStyle(color: Colors.red),
                  ),
                ),
              ],
            ),
          ),

          // 播放列表
          Expanded(
            child: ListView.builder(
              itemCount: viewModel.playlist.length,
              itemBuilder: (context, index) {
                final music = viewModel.playlist[index];
                final isCurrentPlaying = index == viewModel.currentIndex;

                return _buildPlaylistItem(
                  context,
                  music,
                  index,
                  isCurrentPlaying,
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建播放列表项
  Widget _buildPlaylistItem(
    BuildContext context,
    MusicItemModel music,
    int index,
    bool isCurrentPlaying,
  ) {
    return ListTile(
      leading: Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: Colors.grey.shade200,
        ),
        child: music.albumArt != null && music.albumArt!.isNotEmpty
            ? ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(
                  music.albumArt!,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return const Icon(Icons.music_note, color: Colors.grey);
                  },
                ),
              )
            : const Icon(Icons.music_note, color: Colors.grey),
      ),
      title: Text(
        music.title,
        style: TextStyle(
          fontWeight: isCurrentPlaying ? FontWeight.bold : FontWeight.normal,
          color: isCurrentPlaying ? Theme.of(context).primaryColor : null,
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      subtitle: Text(
        music.artist,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      trailing: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 当前播放指示器
          if (isCurrentPlaying)
            Container(
              margin: const EdgeInsets.only(right: 8),
              child: Icon(
                Icons.volume_up,
                color: Theme.of(context).primaryColor,
                size: 20,
              ),
            ),
          // 删除按钮
          IconButton(
            icon: const Icon(Icons.close, size: 20),
            onPressed: () => _removeFromPlaylist(context, index),
          ),
        ],
      ),
      onTap: () {
        // 点击播放该音乐
        viewModel.playAtIndex(index);
        Navigator.of(context).pop();
      },
    );
  }

  /// 从播放列表移除音乐
  void _removeFromPlaylist(BuildContext context, int index) {
    viewModel.removeFromPlaylist(index);

    // 显示撤销提示
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('已从播放列表移除'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  /// 显示清空确认对话框
  void _showClearConfirmDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('清空播放列表'),
        content: const Text('确定要清空所有播放列表吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              viewModel.clearPlaylist();
              Navigator.of(context).pop(); // 关闭对话框
              Navigator.of(context).pop(); // 关闭底部面板
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('清空'),
          ),
        ],
      ),
    );
  }
}

/// 优化的音乐播放页面组件
/// 专为播放列表页面的垂直滑动优化性能
class OptimizedMusicPlayerPage extends StatefulWidget {
  /// 音乐数据
  final MusicItemModel music;

  /// 是否是当前播放的音乐
  final bool isCurrentPlaying;

  /// 是否显示实时进度
  final bool showRealTimeProgress;

  /// 页面索引（用于性能优化）
  final int index;

  const OptimizedMusicPlayerPage({
    super.key,
    required this.music,
    required this.isCurrentPlaying,
    required this.showRealTimeProgress,
    required this.index,
  });

  @override
  State<OptimizedMusicPlayerPage> createState() =>
      _OptimizedMusicPlayerPageState();
}

class _OptimizedMusicPlayerPageState extends State<OptimizedMusicPlayerPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => widget.isCurrentPlaying; // 只保持当前播放页面的状态

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用，用于 AutomaticKeepAliveClientMixin

    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.black, Colors.grey],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      child: SafeArea(
        child: Column(
          children: [
            // 顶部导航栏
            _buildTopBar(),

            // 专辑封面区域
            Expanded(
              flex: 3,
              child: _buildAlbumCoverSection(),
            ),

            // 播放控制区域
            Expanded(
              flex: 2,
              child: _buildPlayerControlsSection(),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopBar() {
    return Container(
      height: kToolbarHeight,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          IconButton(
            icon: const Icon(
              Icons.close_rounded,
              color: Colors.white,
              size: 28,
            ),
            onPressed: () => Navigator.of(context).pop(),
          ),
          const Spacer(),
          // 页面指示器
          Consumer<MusicPlayerViewModel>(
            builder: (context, viewModel, child) {
              return Text(
                '${widget.index + 1} / ${viewModel.playlist.length}',
                style: const TextStyle(
                  color: Colors.white70,
                  fontSize: 14,
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  /// 构建专辑封面区域
  Widget _buildAlbumCoverSection() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 40),
        child: CircularAlbumCoverWidget(
          music: widget.music,
          size: MediaQuery.of(context).size.width - 80,
          showShadow: true,
          enableHeroAnimation: false, // 在列表中禁用英雄动画以提升性能
        ),
      ),
    );
  }

  /// 构建播放控制区域
  Widget _buildPlayerControlsSection() {
    return Padding(
      padding: const EdgeInsets.all(20),
      child: Column(
        children: [
          // 歌曲信息
          _buildSongInfo(),

          const SizedBox(height: 30),

          // 进度条
          _buildProgressSection(),

          const SizedBox(height: 30),

          // 播放控制按钮
          _buildPlaybackControls(),
        ],
      ),
    );
  }

  /// 构建歌曲信息
  Widget _buildSongInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          widget.music.title,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
          textAlign: TextAlign.center,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
        ),
        const SizedBox(height: 8),
        Text(
          widget.music.artist,
          style: const TextStyle(
            color: Colors.white70,
            fontSize: 16,
          ),
          textAlign: TextAlign.center,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

  /// 构建进度条区域
  Widget _buildProgressSection() {
    if (widget.isCurrentPlaying && widget.showRealTimeProgress) {
      // 实时进度条
      return const ProgressSliderWidget(
        activeColor: Colors.white,
        inactiveColor: Colors.white30,
        thumbColor: Colors.white,
        trackHeight: 3.0,
        thumbRadius: 8.0,
        timeLabelStyle: TextStyle(
          color: Colors.white70,
          fontSize: 12,
        ),
      );
    } else {
      // 静态进度条
      return ProgressSliderWidget(
        activeColor: Colors.white,
        inactiveColor: Colors.white30,
        thumbColor: Colors.white,
        trackHeight: 3.0,
        thumbRadius: 8.0,
        timeLabelStyle: const TextStyle(
          color: Colors.white70,
          fontSize: 12,
        ),
        customProgress: 0.0,
        customDuration: widget.music.duration ?? Duration.zero,
        customPosition: Duration.zero,
        onSeek: (position) {
          // 点击静态进度条时切换到该音乐并播放
          if (!mounted) return;
          final viewModel =
              Provider.of<MusicPlayerViewModel>(context, listen: false);
          if (widget.music != viewModel.currentTrack) {
            viewModel.play(widget.music);
          }
          viewModel.seekTo(position);
        },
      );
    }
  }

  /// 构建播放控制按钮
  Widget _buildPlaybackControls() {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            // 播放模式按钮
            ValueListenableBuilder(
              valueListenable: viewModel.playMode,
              builder: (context, playMode, child) {
                return IconButton(
                  icon: Icon(
                    playMode.icon,
                    color: Colors.white,
                    size: 28,
                  ),
                  onPressed: viewModel.togglePlayMode,
                );
              },
            ),

            // 上一首按钮
            IconButton(
              icon: const Icon(
                Icons.skip_previous,
                color: Colors.white,
                size: 32,
              ),
              onPressed: viewModel.canPlayPrevious ? viewModel.previous : null,
            ),

            // 播放/暂停按钮
            _buildMainPlayButton(viewModel),

            // 下一首按钮
            IconButton(
              icon: const Icon(
                Icons.skip_next,
                color: Colors.white,
                size: 32,
              ),
              onPressed: viewModel.canPlayNext ? viewModel.next : null,
            ),

            // 播放列表按钮
            IconButton(
              icon: const Icon(
                Icons.queue_music_rounded,
                color: Colors.white,
                size: 28,
              ),
              onPressed: () {
                // 显示播放列表管理面板
                showModalBottomSheet(
                  context: context,
                  backgroundColor: Colors.transparent,
                  builder: (context) =>
                      PlaylistManagementSheet(viewModel: viewModel),
                );
              },
            ),
          ],
        );
      },
    );
  }

  /// 构建主播放按钮
  Widget _buildMainPlayButton(MusicPlayerViewModel viewModel) {
    return ValueListenableBuilder<bool>(
      valueListenable: viewModel.isPlaying,
      builder: (context, isPlaying, child) {
        // 只有当前播放的音乐才显示实际的播放状态
        final showPlayingState = widget.isCurrentPlaying && isPlaying;

        return Container(
          width: 64,
          height: 64,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(
              color: Colors.white,
              width: 2,
            ),
          ),
          child: Stack(
            alignment: Alignment.center,
            children: [
              // 加载指示器（只在当前播放且正在加载时显示）
              if (widget.isCurrentPlaying && viewModel.isLoading)
                const SizedBox(
                  width: 64,
                  height: 64,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                ),

              // 播放/暂停图标
              IconButton(
                icon: AnimatedSwitcher(
                  duration: const Duration(milliseconds: 200),
                  child: Icon(
                    showPlayingState ? Icons.pause : Icons.play_arrow,
                    key: ValueKey(showPlayingState),
                    color: Colors.white,
                    size: 32,
                  ),
                ),
                onPressed: () {
                  if (!mounted) return;
                  if (widget.isCurrentPlaying) {
                    viewModel.togglePlayPause();
                  } else {
                    // 如果不是当前播放的音乐，切换到该音乐
                    viewModel.play(widget.music);
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }
}
